package com.yisu.expressway.main_page;

import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.reflect.TypeToken;
import com.yisu.expressway.BuildConfig;
import com.yisu.expressway.R;
import com.yisu.expressway.ar.ARActivity;
import com.yisu.expressway.customService.InformationActivity;
import com.yisu.expressway.driver_revelation.activity.RevelationActivity;
import com.yisu.expressway.driver_revelation.model.RevelationMsgCount;
import com.yisu.expressway.fragment.BaseFragment;
import com.yisu.expressway.gas_station.NearByGasStationActivity;
import com.yisu.expressway.location.LocationInfo;
import com.yisu.expressway.location.LocationListener;
import com.yisu.expressway.location.LocationService;
import com.yisu.expressway.login.LoginManager;
import com.yisu.expressway.login.LoginPageActivity;
import com.yisu.expressway.main_page.model.HomeBannerObj;
import com.yisu.expressway.main_page.model.ModuleID;
import com.yisu.expressway.main_page.model.ModuleItem;
import com.yisu.expressway.model.BannerItem;
import com.yisu.expressway.model.LoginEvent;
import com.yisu.expressway.model.VersionControl;
import com.yisu.expressway.more_contact.MoreContactActivity;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.onedollar.activity.GoodsPurchaseActivity;
import com.yisu.expressway.onedollar.activity.OneDollarMainActivity;
import com.yisu.expressway.onedollar.widget.scrolltextview.BaseScrollTextView;
import com.yisu.expressway.onedollar.widget.scrolltextview.ScrollTextView;
import com.yisu.expressway.service_district.MapActivity;
import com.yisu.expressway.service_district.ServiceDistrictListActivity;
import com.yisu.expressway.shopping_mall.ShoppingMallActivity;
import com.yisu.expressway.shopping_mall.YouZanWebActivity;
import com.yisu.expressway.trafficViolation.CarIlegalQueryActivity;
import com.yisu.expressway.ui.BadgeView;
import com.yisu.expressway.ui.UpdateDialog;
import com.yisu.expressway.utils.DisplayUtil;
import com.yisu.expressway.utils.StringUtil;
import com.yisu.expressway.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.hypertrack.smart_scheduler.Job;
import io.hypertrack.smart_scheduler.SmartScheduler;


/**
 * Created by Administrator on 2016/12/8 0008.
 */

public class FragmentHome extends BaseFragment implements  BaseScrollTextView.OnItemClickListener{

    @Bind(R.id.module_list_root_one)
    protected LinearLayout mModuleRootOne;
    @Bind(R.id.module_list_root_two)
    protected LinearLayout mModuleRootTwo;
    @Bind(R.id.tv_scroll_notice)
    protected ScrollTextView mScrollNotice;
    @Bind(R.id.iv_cover)
    protected ImageView mIv_banner;

    private ArrayList<ModuleItem> moduleList = new ArrayList<>();
    ArrayList<View> itemViewList = new ArrayList<>();
    ArrayList<BannerItem> mBannerList = new ArrayList<>();
    ArrayList<HomeBannerObj.NoticeItem> mNoticelist = new ArrayList<>();

    private final static int DEFAULT_GRID_COUNT = 6;
    private final static int JOB_SCHEDULE_INTERVAL = 30 * 60 * 1000;//每隔30分钟获取一次banner列表
    SmartScheduler jobScheduler;

    private View parentView;
    private LocationInfo mLocationInfo;
    private BadgeView mUnReadMsgDot;

    private ModuleID onClickModuleId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if(parentView == null) {
            parentView = inflater.inflate(R.layout.fragment_home, container, false);
        }

        ViewGroup rootView = (ViewGroup) parentView.getParent();
        if (rootView != null) {
            rootView.removeView(parentView);
        }

//        EventBus.getDefault().register(this);
        initBadgeView();
        ButterKnife.bind(this,parentView);
        initModule();
        initModuleItem();
        startRepeatJob();
        return parentView;
    }

    @Override
    public void onResume(){
        super.onResume();
        if(LoginManager.isLoggedIn()) {
            getUnreadMsgCount();
        }
    }

    private void initBadgeView(){
        mUnReadMsgDot = new BadgeView(getActivity());
        mUnReadMsgDot.setShowMsg();
    }

    private void initModule(){

        if(moduleList != null && moduleList.size() > 0){
            return;
        }

        moduleList.add(new ModuleItem(ModuleID.HIGHWAY_CONDITION));
        if(!BuildConfig.CHANNEL_TYPE.equals("xiaomi")) {
            moduleList.add(new ModuleItem(ModuleID.GAS_PAY));
        }
        moduleList.add(new ModuleItem(ModuleID.DRIVER_TIP_OFF));
        moduleList.add(new ModuleItem(ModuleID.SERVICE_DISTRICT));


        /**补齐6个item**/
        int emptyCount = DEFAULT_GRID_COUNT - moduleList.size();
        for(int i = 0; i < emptyCount ; i ++){
            moduleList.add(new ModuleItem(ModuleID.EMPTY_MODULE));
        }

    }

    private void initModuleItem(){
        initViewList(mModuleRootOne);
        initViewList(mModuleRootTwo);

        for(int i = 0; i < moduleList.size() ; i ++){
            final ModuleItem item = moduleList.get(i);
            View mItemParentView = itemViewList.get(i);

            ImageView mIv_icon = (ImageView)mItemParentView.findViewById(R.id.iv_icon);
            TextView mTv_name = (TextView)mItemParentView.findViewById(R.id.tv_name);
            mIv_icon.setVisibility(View.GONE);
            mTv_name.setVisibility(View.GONE);

            if(item.get_img_Id() != -1 && item.getString_Id() != -1){
                mIv_icon.setVisibility(View.VISIBLE);
                mTv_name.setVisibility(View.VISIBLE);

                mIv_icon.setImageResource(item.get_img_Id());
                mTv_name.setText(item.getString_Id());
                mItemParentView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        moduleOnClick(item.getCategory_Id());
                    }
                });

                if(item.getCategory_Id() == ModuleID.DRIVER_TIP_OFF){
                    FrameLayout mIconRoot = (FrameLayout)mItemParentView.findViewById(R.id.module_icon_root);
                    mUnReadMsgDot.setTargetView(mIconRoot);
                    mUnReadMsgDot.setBadgeGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);
                    mUnReadMsgDot.setBadgeMargin(18,8,0,0);
                    mUnReadMsgDot.setVisibility(View.GONE);
                }
            }
        }
    }

    private void initViewList(LinearLayout root){
        for(int i = 0 ; i < 3; i++){
            int itemCount = i * 2;
            View itemParentView = root.getChildAt(itemCount);

            adjustModuleWidth(itemParentView);

            itemViewList.add(itemParentView);
        }
    }

    private void updateBannerView(){

        if(mBannerList != null && mBannerList.size() > 0) {
            Glide.with(getActivity())
                    .load(mBannerList.get(0).imageUrl)
                    .asBitmap()
                    .placeholder(R.color.color_bg_default)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .centerCrop()
                    .into(mIv_banner);
        }

        mScrollNotice.setOnItemClickListener(this);
        if(mNoticelist != null && mNoticelist.size() >0) {
            mScrollNotice.setData(mNoticelist);
        }
    }

    @OnClick(R.id.iv_cover)
    public void go2BannerWeb(){
        if(mBannerList != null && mBannerList.size() > 0){
            BannerItem item = mBannerList.get(0);
            Class mTargetClass = null;
            switch (item.linkType){
                case BannerItem.TYPE_WEB:
                    if (!StringUtil.isNullOrEmpty(item.linkUrl)) {
                        YouZanWebActivity.launch(getActivity(), item.linkUrl, item.title);
                    }
                    break;
                case BannerItem.TYPE_ONEDOLLER_DETAIL:
                    GoodsPurchaseActivity.launch(getActivity(), Long.valueOf(item.linkUrl));
                    break;
                case BannerItem.TYPE_MODULE_AR:
                    mTargetClass = ARActivity.class;
                    break;
                case BannerItem.TYPE_MODULE_CUSTOM_SERVICE:
                    mTargetClass = InformationActivity.class;
                    break;
                case BannerItem.TYPE_MODULE_GAS_STATION:
                    mTargetClass = NearByGasStationActivity.class;
                    break;
                case BannerItem.TYPE_MODULE_HIGHWAY_CONDITION:
                    showTrafficMap();
                    break;
                case BannerItem.TYPE_MODULE_ILLEGAL:
                    mTargetClass = CarIlegalQueryActivity.class;
                    break;
                case BannerItem.TYPE_MODULE_MORE_CONTACT:
                    mTargetClass = MoreContactActivity.class;
                    break;
                case BannerItem.TYPE_MODULE_ONEDOLLER:
                    mTargetClass = OneDollarMainActivity.class;
                    break;
                case BannerItem.TYPE_MODULE_SERVICE_DISTRICT:
                    mTargetClass = ServiceDistrictListActivity.class;
                    break;
                case BannerItem.TYPE_MODULE_SHOPPING_MALL:
                    mTargetClass = ShoppingMallActivity.class;
                    break;

            }

            if(mTargetClass != null){
                startTargetActivity(mTargetClass);
            }

        }
    }


    @Override
    public void onItemClick(int position, TextView textView) {
        if(mNoticelist != null && !mNoticelist.isEmpty()) {
            HomeBannerObj.NoticeItem item = mNoticelist.get(position);
            jump2NoticeLinkPage(item);
        }
    }

    private void showTrafficMap(){
        mLocationInfo = LocationService.getInstance().getLocationResult();
        if(mLocationInfo == null){
            showLoading();
            LocationService.getInstance().start(new LocationListener() {
                @Override
                public void onSuccess(LocationInfo info) {
                    dismissLoading();
                    mLocationInfo = info;
                    MapActivity.launchTraffic(getActivity(), mLocationInfo.getLongitude(),mLocationInfo.getLatitude());
                }

                @Override
                public void onFailure(int errorCode, String errorMessage) {
                    ToastUtil.displayShortToastMsg(getActivity(),errorMessage);
                }
            });
        }else {
            MapActivity.launchTraffic(getActivity(), mLocationInfo.getLongitude(),mLocationInfo.getLatitude());
        }
    }

    private void jump2NoticeLinkPage(HomeBannerObj.NoticeItem item){
        switch (item.type){
            case HomeBannerObj.NOTICE_TYPE_WEB:
                YouZanWebActivity.launch(getActivity(),item.url,item.title);
                break;
            case HomeBannerObj.NOTICE_TYPE_TEXT:
                break;
            default:
                break;
        }
    }

    private void moduleOnClick(ModuleID moduleId) {
        Class mTargetClass = null;
        onClickModuleId = moduleId;
        switch (moduleId){
            case HIGHWAY_CONDITION:
                showTrafficMap();
                return;
            case GAS_PAY:
                break;
            case DRIVER_TIP_OFF:
                if(LoginManager.isLoggedIn()) {
                    mTargetClass = RevelationActivity.class;
                }else {
                    mTargetClass = LoginPageActivity.class;
                }
                break;
            case SERVICE_DISTRICT:
                mTargetClass = ServiceDistrictListActivity.class;
                break;
            default:
                break;
        }

        if(mTargetClass != null){
            startTargetActivity(mTargetClass);
        }else {
            ToastUtil.displayShortToastMsg(getActivity(),R.string.action_is_developing);
        }
    }

//    @Subscribe
//    public void onReceiverLoginEvent(LoginEvent event){
//        if(event.getLoginResult()){
//            if(onClickModuleId == ModuleID.DRIVER_TIP_OFF){
//                startTargetActivity(RevelationActivity.class);
//            }
//        }
//    }

    protected void adjustModuleWidth(View view){
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        int mModuleItemWidth = (mScreenWidth- DisplayUtil.dip2px(getActivity(),10) - 2) / 3;
        lp.width = mModuleItemWidth;
        lp.height = DisplayUtil.dip2px(getActivity(),125) - NavigationBarHeight / 2;
        view.setLayoutParams(lp);
    }

    private void getHomeBanner(){

        Map<String, Object> params = new HashMap();
        params.put("moduleType",TabBaseFragment.TAB_HOME);

        ApiClientHelper.postApi(ApiSetting.getHomeBannerList(), new TypeToken<HomeBannerObj>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<HomeBannerObj>>() {
            @Override
            public void onResponse(ApiResult<HomeBannerObj> result) {

                dismissLoading();

                if (!result.success) {
                    ToastUtil.displayLongToastMsg(getActivity(), result.getMsg());
                    return;
                }

                HomeBannerObj mBannerListObj = result.getResult();
                if(mBannerListObj != null){
                    mBannerList = mBannerListObj.advertisementVos;
                    mNoticelist = mBannerListObj.announcementVos;
                    updateBannerView();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismissLoading();
                ToastUtil.displayShortToastMsg(getActivity(), volleyError.getMessage());
            }
        }, this);
    }

    /**
     * 定时获取banner任务回调
     */
    SmartScheduler.JobScheduledCallback callback = new SmartScheduler.JobScheduledCallback() {
        @Override
        public void onJobScheduled(Context context, Job job) {
            getHomeBanner();
        }
    };

    private void startRepeatJob(){
        jobScheduler = SmartScheduler.getInstance(getActivity());
        if(jobScheduler.contains(TabBaseFragment.TAB_HOME)){
            jobScheduler.removeJob(TabBaseFragment.TAB_HOME);
        }

        Job job = createJob();
        if(job != null){
            jobScheduler.addJob(job);
        }

    }

    private Job  createJob(){
        Job.Builder builder = new Job.Builder(TabBaseFragment.TAB_HOME, callback, Job.Type.JOB_TYPE_HANDLER, String.valueOf(TabBaseFragment.TAB_HOME))
                .setRequiredNetworkType(Job.NetworkType.NETWORK_TYPE_ANY)
                .setIntervalMillis(JOB_SCHEDULE_INTERVAL);
        builder.setPeriodic(JOB_SCHEDULE_INTERVAL);

        return builder.build();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser){

        } else {

        }
    }


    @Override
    public void onDestroyView(){
        super.onDestroyView();
        ButterKnife.unbind(this);
//        EventBus.getDefault().unregister(this);
        if(jobScheduler != null){
            if(jobScheduler.contains(TabBaseFragment.TAB_HOME)){
                jobScheduler.removeJob(TabBaseFragment.TAB_HOME);
            }
            jobScheduler = null;
        }
    }

    private void getUnreadMsgCount(){
        ApiClientHelper.postApi(ApiSetting.getUnreadMsgCount(), new TypeToken<RevelationMsgCount>() {
        }, new JSONObject(new HashMap()), new Response.Listener<ApiResult<RevelationMsgCount>>() {
            @Override
            public void onResponse(ApiResult<RevelationMsgCount> result) {
                if (!result.success) {
                    ToastUtil.displayShortToastMsg(result.getMsg());
                    return;
                }

                RevelationMsgCount msgCount = result.getResult();
                if(msgCount != null && msgCount.sumNum > 0){
                    mUnReadMsgDot.setVisibility(View.VISIBLE);
                    mUnReadMsgDot.setText(String.valueOf(msgCount.sumNum));
                }else {
                    mUnReadMsgDot.setVisibility(View.GONE);
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtil.displayShortToastMsg(volleyError.getMessage());
            }
        }, this);
    }

}
